package com.jufa_3.common;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.jufa_3.dto.CollectInfo;
import com.jufa_3.dto.SelectInfo;
import com.jufa_3.service.SelectInterface;
import org.apache.commons.lang.StringUtils;
import org.assertj.core.util.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;

@Repository
@PropertySource(value = "classpath:pdf-titles.properties", encoding = "UTF-8")
public class PDFTool {

    @Resource
    private Environment config;

    @Autowired
    private SelectInterface selectInterface;

    public void getComPDF(SelectInfo sif, HttpServletResponse response) {
        sif.setSourceType("PDF_SE");
        // 生成导出PDF的文件名称
        String fileName = "聚法企业信息（" + sif.getComValue() + "）.pdf";
        // 设置响应头
        response.setContentType("application/pdf");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        JSONObject companyInfo = JSONObject.parseObject(selectInterface.getCompanyInfo(sif).getReturnJO().toString());
        JSONArray items = JSONArray.parseArray(config.getProperty("comItems"));
        // 1.新建document对象
        Document document = new Document();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
            // 3.打开文档
            document.open();
            //中文字体,解决中文不能显示问题
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font font = new Font(bfChinese);
            document.addTitle("聚法企业信息");
            //作者
            document.addAuthor("天启数科");
            //主题
            document.addSubject("聚法企业信息");
            //关键字
            document.addKeywords(fileName);
            //创建时间
            document.addCreationDate();
            //应用程序
            document.addCreator("微信小程序：聚法风控宝");
            Paragraph title = new Paragraph("企业信息(聚法风控宝)", getFont(30));
            title.setAlignment(Element.ALIGN_CENTER);
            document.add(title);
            Paragraph selectName = new Paragraph("关键字：" + sif.getComValue(), getFont(20));
            selectName.setAlignment(Element.ALIGN_CENTER);
            document.add(selectName);
            Paragraph selectCardId = new Paragraph("关键字类型编号：" + sif.getComType(), getFont(20));
            selectCardId.setAlignment(Element.ALIGN_CENTER);
            document.add(selectCardId);
            Paragraph selectTime = new Paragraph("查询时间：" + new SimpleDateFormat("yyyy-MM-dd hh:mm").format(new Date()), getFont(20));
            selectTime.setAlignment(Element.ALIGN_CENTER);
            document.add(selectTime);
            List<PdfPTable> detailTables = new ArrayList<>();
            Integer sumCount = 0;
            for (int i = 0; i < items.size(); i++) {
                String eName = items.getJSONObject(i).getString("eName");
                String cName = items.getJSONObject(i).getString("cName");
                JSONArray titles = items.getJSONObject(i).getJSONArray("titles");
                JSONArray entrysInfo = new JSONArray();
                if ("base".equals(eName) || "caipanwenshu".equals(eName) || "contactInfo".equals(eName) || "industry".equals(eName)) {
                    if (companyInfo.containsKey(eName)){
                        entrysInfo.add(companyInfo.getJSONObject(eName));
                    }
                } else {
                    entrysInfo = companyInfo.getJSONArray(eName);
                }
                Integer count = entrysInfo != null  ? entrysInfo.size() : 0;
                sumCount += count;
                PdfPTable table = new PdfPTable(5);
                table.setWidthPercentage(100); // 宽度100%填充
                table.setSpacingBefore(35f); // 前间距
                List<PdfPRow> listRow = table.getRows();
                PdfPCell cells1[] = new PdfPCell[5];
                cells1[0] = new PdfPCell(new Paragraph(cName + "（" + count + "条）", font));//单元格内容
                cells1[0].setBorderColor(BaseColor.BLUE);//边框验证
                cells1[0].setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
                cells1[0].setVerticalAlignment(Element.ALIGN_MIDDLE);   //垂直居中
                cells1[0].setColspan(5);
                cells1[0].setPadding(7);
                listRow.add(new PdfPRow(cells1));
                for (int j = 0; j < count; j++) {
                    // 每条数据做整合编辑
                    JSONObject entryInfo = entrysInfo.getJSONObject(j);
                    for (int k = 0; k < titles.size(); k++) {
                        String ctitle = titles.getJSONArray(k).getString(0);
                        String etitle = titles.getJSONArray(k).getString(1);
                        listRow.add(new PdfPRow(getPdfPCells(ctitle, entryInfo.getString(etitle))));
                    }
                    // 添加空行
                    listRow.add(new PdfPRow(getPdfPNullCells()));
                }
                detailTables.add(table);
            }
            Paragraph sum = new Paragraph("合计" + sumCount + "条线索", getFont(18));
            sum.setAlignment(Element.ALIGN_CENTER);
            document.add(sum);
            // 各项详细数据表格
            for (PdfPTable table : detailTables)
                document.add(table);
            // 5.关闭文档
            document.close();
            // 关闭书写器
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getTakeOfficePDF(SelectInfo sif, HttpServletResponse response) {
        sif.setSourceType("PDF_SE");
        // 生成导出PDF的文件名称
        String fileName = "聚法任职信息（**" + sif.getName().substring(1) + "）.pdf";
        // 设置响应头
        response.setContentType("application/pdf");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        JSONArray qyrzInfos = (JSONArray) selectInterface.getCompanyPostInfo(sif).getReturnJO();
        JSONArray qyrztitles = JSONArray.parseArray(config.getProperty("qyrztitles"));
        // 1.新建document对象
        Document document = new Document();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
            // 3.打开文档
            document.open();
            //中文字体,解决中文不能显示问题
            document.addTitle("企业任职");
            //作者
            document.addAuthor("天启数科");
            //主题
            document.addSubject("企业任职");
            //关键字
            document.addKeywords("企业任职");
            //创建时间
            document.addCreationDate();
            //应用程序
            document.addCreator("微信小程序：聚法风控宝");
            Paragraph title = new Paragraph("个人任职分析(聚法风控宝)", getFont(30));
            title.setAlignment(Element.ALIGN_CENTER);
            document.add(title);
            Paragraph selectName = new Paragraph("姓名：" + "*" + sif.getName().substring(sif.getName().length() - 2), getFont(20));
            selectName.setAlignment(Element.ALIGN_CENTER);
            document.add(selectName);
            Paragraph selectCardId = new Paragraph("身份证：" + "***" + sif.getCardNum().substring(sif.getCardNum().length() - 8), getFont(20));
            selectCardId.setAlignment(Element.ALIGN_CENTER);
            document.add(selectCardId);
            Paragraph selectTime = new Paragraph("查询时间：" + new SimpleDateFormat("yyyy-MM-dd hh:mm").format(new Date()), getFont(20));
            selectTime.setAlignment(Element.ALIGN_CENTER);
            document.add(selectTime);
            // 数据汇集模板准备
            List<PdfPCell[]> cellsAll = new ArrayList<>();
            Paragraph sum = new Paragraph("合计任职企业：" + qyrzInfos.size() + " 家", getFont(20));
            sum.setAlignment(Element.ALIGN_CENTER);
            sum.setSpacingAfter(8f);
            document.add(sum);
            // 汇集表格
            PdfPTable huijitable = new PdfPTable(3);
            List<PdfPRow> listRow = huijitable.getRows();
            for (int i = 0; i < qyrzInfos.size(); i++) {
                JSONObject qyrzInfo = qyrzInfos.getJSONObject(i);
                JSONObject stockHolderItem = qyrzInfo.getJSONObject("stockHolderItem");
                JSONObject basicInfo = qyrzInfo.getJSONObject("basicInfo");
                PdfPCell cells[] = new PdfPCell[3];
                cells[0] = new PdfPCell(new Phrase("第" + (i + 1) + "家任职企业：" + qyrzInfo.getJSONObject("basicInfo").getString("name"), getFont(15)));
                cells[0].setColspan(3);
                listRow.add(new PdfPRow(setCell(cells)));
                JSONArray gg = new JSONArray();
                for (int j = 0; j < qyrztitles.size(); j++) {
                    if (j == 0) {
                        PdfPCell cellsone[] = new PdfPCell[3];
                        cellsone[0] = new PdfPCell(new Phrase(qyrztitles.getJSONObject(j).getString("cName"), getFont(14)));
                        JSONArray array = JSONArray.parseArray(qyrzInfo.getString(qyrztitles.getJSONObject(j).getString("eName")));
                        String relationshipStr = "";
                        for (int k = 0; k < array.size(); k++) {
                            if ("sh".equals(array.getString(k))) {
                                relationshipStr += "企业股东；";
                            } else if ("lp".equals(array.getString(k))) {
                                relationshipStr += "企业法人；";
                            } else if ("tm".equals(array.getString(k))) {
                                relationshipStr += "企业高管；";
                            }
                        }
                        cellsone[1] = new PdfPCell(new Phrase(relationshipStr != null ? relationshipStr : "未检索到", getFont(15)));
                        cellsone[1].setColspan(2);
                        listRow.add(new PdfPRow(setCell(cellsone)));
                    } else if (j > 0 && j < 6) {
                        if (stockHolderItem != null) {
                            if (j == 1) {
                                PdfPCell cellsj[] = new PdfPCell[3];
                                cellsj[0] = new PdfPCell(new Phrase("此人对该公司持股信息", getFont(14)));
                                cellsj[0].setRowspan(5);
                                cellsj[1] = new PdfPCell(new Phrase(qyrztitles.getJSONObject(j).getString("cName"), getFont(14)));
                                cellsj[2] = new PdfPCell(new Phrase(stockHolderItem.getString(qyrztitles.getJSONObject(j).getString("eName")), getFont(15)));
                                listRow.add(new PdfPRow(setCell(cellsj)));
                            } else {
                                listRow.add(new PdfPRow(setCell(extracted(qyrztitles.getJSONObject(j).getString("cName"), stockHolderItem.getString(qyrztitles.getJSONObject(j).getString("eName"))))));
                            }
                        }
                    } else {
                        if (j == 6) {
                            PdfPCell cellso[] = new PdfPCell[3];
                            cellso[0] = new PdfPCell(new Phrase("此人所在公司的基本信息", getFont(14)));
                            int size = basicInfo.getJSONArray("staffList") != null ? basicInfo.getJSONArray("staffList").size() : 0;
                            cellso[0].setRowspan(12 + 4 * size);
                            cellso[1] = new PdfPCell(new Phrase(qyrztitles.getJSONObject(j).getString("cName"), getFont(14)));
                            cellso[2] = new PdfPCell(new Phrase(basicInfo.getString(qyrztitles.getJSONObject(j).getString("eName")), getFont(15)));
                            listRow.add(new PdfPRow(setCell(cellso)));
                        } else if (j > 17) {
                            gg.add(qyrztitles.getJSONObject(j));
                        } else {
                            listRow.add(new PdfPRow(setCell(extracted(qyrztitles.getJSONObject(j).getString("cName"), basicInfo.getString(qyrztitles.getJSONObject(j).getString("eName"))))));
                        }
                    }
                }
                // 单独的高管数据
                JSONArray staffList = basicInfo.getJSONArray("staffList");
                if (staffList != null) {
                    for (int j = 0; j < staffList.size(); j++) {
                        PdfPCell cellsgg[] = new PdfPCell[3];
                        cellsgg[1] = new PdfPCell(new Phrase("第" + (j + 1) + "位高管", getFont(14)));
                        cellsgg[1].setColspan(2);
                        listRow.add(new PdfPRow(setCell(cellsgg)));
                        for (int k = 0; k < gg.size(); k++) {
                            listRow.add(new PdfPRow(setCell(extracted(gg.getJSONObject(k).getString("cName"), staffList.getJSONObject(j).getString(gg.getJSONObject(k).getString("eName"))))));

                        }
                    }
                }
            }
            huijitable.setWidthPercentage(100);  // 宽度100%填充
            huijitable.setSpacingAfter(25f);    // 前间距
            float[] columnWidths = {1.2f, 1.7f, 3f};
            huijitable.setWidths(columnWidths);
            document.add(huijitable);
            // 5.关闭文档
            document.close();
            // 关闭书写器
            writer.close();
        }  catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getGrajPDF(SelectInfo sif, HttpServletResponse response) {
        sif.setSourceType("PDF_SE");
        // 生成导出PDF的文件名称
        String fileName = "聚法高阶版司法失信分析（**" + sif.getName().substring(sif.getName().length() - 1) + "）.pdf";
        // 设置响应头
        response.setContentType("application/pdf");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        JSONArray detail = selectInterface.zewuGrajjcxxhy(sif).getJSONArray("detail");
        JSONObject companyInfo = detail.getJSONObject(0);
        JSONArray items = JSONArray.parseArray(config.getProperty("grajtitles"));
        // 1.新建document对象
        Document document = new Document();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
            // 3.打开文档
            document.open();
            //中文字体,解决中文不能显示问题
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font font = new Font(bfChinese);
            document.addTitle("聚法高阶版司法失信分析");
            //作者
            document.addAuthor("天启数科");
            //主题
            document.addSubject("聚法高阶版司法失信分析");
            //关键字
            document.addKeywords(fileName);
            //创建时间
            document.addCreationDate();
            //应用程序
            document.addCreator("微信小程序：聚法风控宝");
            Paragraph title = new Paragraph("高阶版司法信息(聚法风控宝)", getFont(30));
            title.setAlignment(Element.ALIGN_CENTER);
            document.add(title);
            Paragraph selectName = new Paragraph("姓名：" + "*" + sif.getName().substring(sif.getName().length() - 2), getFont(20));
            selectName.setAlignment(Element.ALIGN_CENTER);
            document.add(selectName);
            Paragraph selectCardId = new Paragraph("身份证：" + "***" + sif.getCardNum().substring(sif.getCardNum().length() - 8), getFont(20));
            selectCardId.setAlignment(Element.ALIGN_CENTER);
            document.add(selectCardId);
            Paragraph selectTime = new Paragraph("查询时间：" + new SimpleDateFormat("yyyy-MM-dd hh:mm").format(new Date()), getFont(20));
            selectTime.setAlignment(Element.ALIGN_CENTER);
            document.add(selectTime);
            List<PdfPTable> detailTables = new ArrayList<>();
            Integer sumCount = 0;
            for (int i = 0; i < items.size(); i++) {
                String eName = items.getJSONObject(i).getString("eName");
                String cName = items.getJSONObject(i).getString("cName");
                JSONArray titles = items.getJSONObject(i).getJSONArray("titles");

                JSONArray entrysInfo = new JSONArray();
                if (companyInfo.getJSONObject(eName).containsKey("cases")){
                    entrysInfo = companyInfo.getJSONObject(eName).getJSONArray("cases");
                }
                sumCount += entrysInfo.size();
                PdfPTable table = new PdfPTable(5);
                table.setWidthPercentage(100); // 宽度100%填充
                table.setSpacingBefore(35f); // 前间距
                List<PdfPRow> listRow = table.getRows();
                PdfPCell cells1[] = new PdfPCell[5];
                cells1[0] = new PdfPCell(new Paragraph(cName + "（" + entrysInfo.size() + "条）", font));//单元格内容
                cells1[0].setBorderColor(BaseColor.BLUE);//边框验证
                cells1[0].setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
                cells1[0].setVerticalAlignment(Element.ALIGN_MIDDLE);   //垂直居中
                cells1[0].setColspan(5);
                cells1[0].setPadding(7);
                listRow.add(new PdfPRow(cells1));
                for (int j = 0; j < entrysInfo.size(); j++) {
                    // 每条数据做整合编辑
                    JSONObject entryInfo = entrysInfo.getJSONObject(j);
                    for (int k = 0; k < titles.size(); k++) {
                        String etitle = titles.getJSONArray(k).getString(0);
                        String ctitle = titles.getJSONArray(k).getString(1);
                        listRow.add(new PdfPRow(getPdfPCells(ctitle, entryInfo.getString(etitle))));
                    }
                    // 添加空行
                    listRow.add(new PdfPRow(getPdfPNullCells()));
                }
                detailTables.add(table);
            }
            Paragraph sum = new Paragraph("合计" + sumCount + "条线索", getFont(18));
            sum.setAlignment(Element.ALIGN_CENTER);
            document.add(sum);
            // 各项详细数据表格
            for (PdfPTable table : detailTables)
                document.add(table);
            // 5.关闭文档
            document.close();
            // 关闭书写器
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getSiFaPDF(SelectInfo sif, HttpServletResponse response) {
        sif.setSourceType("PDF_SE");
        // 生成导出PDF的文件名称
        String fileName = "聚法司法失信分析（**" + sif.getName().substring(sif.getName().length() - 1) + "）.pdf";
        // 设置响应头
        response.setContentType("application/pdf");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        JSONObject personalLIstInfo = selectInterface.zewuFyxxxq(sif).getJSONObject("message").getJSONObject("data");
        JSONObject huiji = JSONObject.parseObject(config.getProperty("huiji"));
        JSONArray items = JSONArray.parseArray(config.getProperty("items"));
        // 1.新建document对象
        Document document = new Document();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
            // 3.打开文档
            document.open();
            //中文字体,解决中文不能显示问题
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font font = new Font(bfChinese);
            document.addTitle("司法失信分析");
            //作者
            document.addAuthor("天启数科");
            //主题
            document.addSubject("个人司法失信分析");
            //关键字
            document.addKeywords(fileName);
            //创建时间
            document.addCreationDate();
            //应用程序
            document.addCreator("微信小程序：聚法风控宝");
            Paragraph title = new Paragraph("司法失信分析(聚法风控宝)", getFont(30));
            title.setAlignment(Element.ALIGN_CENTER);
            document.add(title);
            Paragraph selectName = new Paragraph("姓名：" + "*" + sif.getName().substring(sif.getName().length() - 2), getFont(20));
            selectName.setAlignment(Element.ALIGN_CENTER);
            document.add(selectName);
            Paragraph selectCardId = new Paragraph("身份证：" + "***" + sif.getCardNum().substring(sif.getCardNum().length() - 8), getFont(20));
            selectCardId.setAlignment(Element.ALIGN_CENTER);
            document.add(selectCardId);
            Paragraph selectTime = new Paragraph("查询时间：" + new SimpleDateFormat("yyyy-MM-dd hh:mm").format(new Date()), getFont(20));
            selectTime.setAlignment(Element.ALIGN_CENTER);
            document.add(selectTime);
            // 数据汇集模板准备
            List<PdfPCell[]> cellsAll = new LinkedList<>();
            List<PdfPCell[]> cellsPart = new LinkedList<>();
            // 每一类数据详情
            List<PdfPTable> detailTables = new ArrayList<>();
            Integer sumCount = 0;
            for (int i = 0; i < items.size(); i++) {
                String eName = items.getJSONObject(i).getString("eName");
                String cName = items.getJSONObject(i).getString("cName");
                JSONArray titles = items.getJSONObject(i).getJSONArray("titles");
                JSONArray entrysInfo = personalLIstInfo.getJSONArray(eName);
                Integer count = entrysInfo != null ? entrysInfo.size() : 0;
                sumCount += count;
                for (int hj = 0; hj < huiji.getJSONArray(eName).size() + 1; hj++) {
                    cellsPart.removeAll(cellsAll);
                    PdfPCell cells[] = new PdfPCell[2];
                    if (hj == 0) {
                        cells[0] = new PdfPCell(new Paragraph(cName + "(" + count + "条)", font));
                        if (count > 0) {
                            cells[0].setBorderColor(BaseColor.RED);
                        }
                        cells[0].setColspan(2);
                    } else {
                        cells[0] = new PdfPCell(new Paragraph(huiji.getJSONArray(eName).getString(hj - 1), font)); //单元格内容
                    }
                    cellsPart.add(cells);
                }
                PdfPTable table = new PdfPTable(5);
                table.setWidthPercentage(100); // 宽度100%填充
                table.setSpacingBefore(35f); // 前间距
                List<PdfPRow> listRow = table.getRows();
                PdfPCell cells1[] = new PdfPCell[5];
                cells1[0] = new PdfPCell(new Paragraph(cName + "（" + count + "条）", font));//单元格内容
                cells1[0].setBorderColor(BaseColor.BLUE);//边框验证
                cells1[0].setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
                cells1[0].setVerticalAlignment(Element.ALIGN_MIDDLE);   //垂直居中
                cells1[0].setColspan(5);
                cells1[0].setPadding(7);
                listRow.add(new PdfPRow(cells1));
                CollectInfo collectInfo = null;
                if (entrysInfo != null) {
                    collectInfo = new CollectInfo(entrysInfo.getJSONObject(0).getLong("SortTime"));
                }
                for (int j = 0; j < count; j++) {
                    // 每条数据做整合编辑
                    JSONObject entryInfo = entrysInfo.getJSONObject(j);
                    for (int k = 0; k < titles.size(); k++) {
                        String etitle = titles.getJSONArray(k).getString(0);
                        String ctitle = titles.getJSONArray(k).getString(1);
                        listRow.add(new PdfPRow(getPdfPCells(ctitle, entryInfo.getString(etitle))));
                    }
                    // 添加空行
                    listRow.add(new PdfPRow(getPdfPNullCells()));
                    if (entryInfo.getLong("SortTime") < collectInfo.getPioneer()) {
                        collectInfo.setPioneer(entryInfo.getLong("SortTime"));
                        collectInfo.setPioneerIndex(j);
                    }
                    if (entryInfo.getLong("SortTime") > collectInfo.getRecently()) {
                        collectInfo.setRecently(entryInfo.getLong("SortTime"));
                        collectInfo.setRecentlyIndex(j);
                    }
                    collectInfo.setMatchRatio(collectInfo.getMatchRatio() + entryInfo.getFloat("MatchRatio"));
                    // 单独各项
                    if ("zxgg".equals(eName) && count > 0) {
                        Long execMoney = entryInfo.getLong("ExecMoney");
                        if (j == 0) {
                            collectInfo.setMaxMoney(execMoney);
                            collectInfo.setMinMoney(execMoney);
                        } else {
                            if (execMoney > collectInfo.getMaxMoney()) {
                                collectInfo.setMaxMoney(execMoney);
                            }
                            if (execMoney < collectInfo.getMinMoney()) {
                                collectInfo.setMinMoney(execMoney);
                            }
                        }
                        collectInfo.setSumMoney(collectInfo.getSumMoney() + execMoney);
                        collectInfo.caseState.add(entryInfo.getString("caseState"));
                    } else if ("shixin".equals(eName) && count > 0) {
                        collectInfo.lxqk.add(entryInfo.getString("lxqk"));
                    } else if ("cpws".equals(eName) && count > 0) {
                        collectInfo.caseType.add(entryInfo.getString("caseType"));
                        collectInfo.caseCause.add(entryInfo.getString("caseCause"));
                    } else if ("bgt".equals(eName) && count > 0) {
                        Integer execMoney = entryInfo.getInteger("execMoney");
                        Integer unexecMoney = entryInfo.getInteger("unexecMoney");
                        if (execMoney != null) {
                            collectInfo.setExecMoney(collectInfo.getExecMoney() + execMoney);
                        }
                        if (unexecMoney != null) {
                            collectInfo.setUnnexeMoney(collectInfo.getUnnexeMoney() + unexecMoney);
                        }
                    } else if ("wdhmd".equals(eName) && count > 0) {
                        Float whfx = entryInfo.getFloat("whfx");
                        Float bjbx = entryInfo.getFloat("bjbx");
                        Float yhje = entryInfo.getFloat("yhje");
                        if (whfx != null) {
                            collectInfo.setWhfxMoney(collectInfo.getWhfxMoney() + whfx);
                        }
                        if (bjbx != null) {
                            collectInfo.setBjbxMoney(collectInfo.getBjbxMoney() + bjbx);
                        }
                        if (yhje != null) {
                            collectInfo.setYhjeMoney(collectInfo.getYhjeMoney() + yhje);
                        }
                    } else if ("ajlc".equals(eName) && count > 0) {
                        collectInfo.ajztCause.add(entryInfo.getString("caseStatus"));
                        collectInfo.slztCause.add(entryInfo.getString("ajlcStatus"));
                    }
                }
                if (count > 0) {
                    int timeDiffren = (int) ((collectInfo.getRecently() - collectInfo.getPioneer()) / (1000 * 24 * 60 * 60));
                    JSONObject recentlyInfo = entrysInfo.getJSONObject(collectInfo.getRecentlyIndex());
                    JSONObject pioneerInfo = entrysInfo.getJSONObject(collectInfo.getPioneerIndex());
                    String recently = recentlyInfo.getString("SortTimeString");
                    String pioneer = pioneerInfo.getString("SortTimeString");
                    cellsPart.get(3)[1] = new PdfPCell(new Paragraph(timeDiffren + "天", font));
                    cellsPart.get(4)[1] = new PdfPCell(new Paragraph((collectInfo.getMatchRatio() / count) * 100 + "%", font));
                    // 对汇集数据写入
                    if ("shixin".equals(eName)) {
                        recently += " " + recentlyInfo.getString("jtqx");
                        pioneer += " " + pioneerInfo.getString("jtqx");
                        cellsPart.get(5)[1] = new PdfPCell(new Paragraph(getCount(collectInfo.getLxqk(), null), font));
                        cellsPart.get(6)[1] = new PdfPCell(new Paragraph(getCount(collectInfo.getJizhongLocation(), null), font));
                    } else if ("fygg".equals(eName)) {
                        recently += " " + recentlyInfo.getString("Body");
                        pioneer += " " + pioneerInfo.getString("Body");
                    } else if ("zxgg".equals(eName)) {
                        recently += " " + recentlyInfo.getString("Title");
                        pioneer += " " + pioneerInfo.getString("Title");
                        cellsPart.get(5)[1] = new PdfPCell(new Paragraph(collectInfo.getMaxMoney().toString() + "元", font));
                        cellsPart.get(6)[1] = new PdfPCell(new Paragraph(collectInfo.getMinMoney().toString() + "元", font));
                        cellsPart.get(7)[1] = new PdfPCell(new Paragraph(collectInfo.getSumMoney().toString() + "元", font));
                        cellsPart.get(8)[1] = new PdfPCell(new Paragraph(getCount(collectInfo.caseState, "zxgg"), font));
                    } else if ("cpws".equals(eName)) {
                        recently += " " + recentlyInfo.getString("Title");
                        pioneer += " " + pioneerInfo.getString("Title");
                        cellsPart.get(5)[1] = new PdfPCell(new Paragraph(getCount(collectInfo.getCaseType(), "cpws_1"), font));
                        cellsPart.get(6)[1] = new PdfPCell(new Paragraph(getCount(collectInfo.caseCause, "cpws_2"), font));
                    } else if ("ktgg".equals(eName)) {
                        recently += " " + recentlyInfo.getString("Title");
                        pioneer += " " + pioneerInfo.getString("Title");
                    } else if ("bgt".equals(eName)) {
                        recently += " " + recentlyInfo.getString("Body");
                        pioneer += " " + pioneerInfo.getString("Body");
                        cellsPart.get(5)[1] = new PdfPCell(new Paragraph(collectInfo.getExecMoney() != null ? collectInfo.getExecMoney().toString() : "暂未统计到", font));
                        cellsPart.get(6)[1] = new PdfPCell(new Paragraph(collectInfo.getUnnexeMoney() != null ? collectInfo.getUnnexeMoney().toString() : "暂未统计到", font));
                    } else if ("wdhmd".equals(eName)) {
                        recently += " " + recentlyInfo.getString("Title");
                        pioneer += " " + pioneerInfo.getString("Title");
                        cellsPart.get(5)[1] = new PdfPCell(new Paragraph(collectInfo.getWhfxMoney() != null ? collectInfo.getWhfxMoney().toString() : "暂未统计到", font));
                        cellsPart.get(6)[1] = new PdfPCell(new Paragraph(collectInfo.getBjbxMoney() != null ? collectInfo.getBjbxMoney().toString() : "暂未统计到", font));
                        cellsPart.get(7)[1] = new PdfPCell(new Paragraph(collectInfo.getYhjeMoney() != null ? collectInfo.getYhjeMoney().toString() : "暂未统计到", font));
                    } else if ("ajlc".equals(eName)) {
                        recently += " " + recentlyInfo.getString("Title");
                        pioneer += " " + pioneerInfo.getString("Title");
                        cellsPart.get(5)[1] = new PdfPCell(new Paragraph("此项无数据", font));
                        cellsPart.get(6)[1] = new PdfPCell(new Paragraph("此项无数据", font));
                    }
                    cellsPart.get(1)[1] = new PdfPCell(new Paragraph(pioneer, font));
                    cellsPart.get(2)[1] = new PdfPCell(new Paragraph(recently, font));
                }
                for (int j = 0; j < cellsPart.size(); j++) {
                    for (int k = 0; k < cellsPart.get(j).length; k++) {
                        if (cellsPart.get(j)[k] == null) {
                            cellsPart.get(j)[k] = new PdfPCell(new Paragraph("此项无数据", font));
                        }
                    }
                }
                cellsAll.addAll(cellsPart);
                detailTables.add(table);
            }
            // 添加汇集表格
            PdfPTable huijitable = new PdfPTable(2);
            huijitable.setWidthPercentage(100);  // 宽度100%填充
            huijitable.setSpacingAfter(25f);    // 前间距
            List<PdfPRow> listRow = huijitable.getRows();
            for (PdfPCell[] cells : cellsAll) {
                listRow.add(new PdfPRow(setCell(cells)));
            }
            float[] columnWidths = {1.2f, 3f};
            huijitable.setWidths(columnWidths);
            Paragraph sum = new Paragraph("合计" + sumCount + "条线索", getFont(18));
            sum.setAlignment(Element.ALIGN_CENTER);
            document.add(sum);
            // 分析数据表格
            Paragraph hzfx = new Paragraph("汇总分析", getFont(18));
            hzfx.setAlignment(Element.ALIGN_CENTER);
            hzfx.setSpacingBefore(12f);
            hzfx.setSpacingAfter(8f);
            document.add(hzfx);
            document.add(huijitable);
            Paragraph xiangxi = new Paragraph("详细司法数据(关键字:*" + sif.getName().substring(sif.getName().length() - 2) + ")", getFont(18));
            xiangxi.setAlignment(Element.ALIGN_CENTER);
            document.add(xiangxi);
            // 各项详细数据表格
            for (PdfPTable table : detailTables) {
                document.add(table);
            }
            // 5.关闭文档
            document.close();
            // 关闭书写器
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private PdfPCell[] extracted(String title, String value) throws DocumentException, IOException {
        PdfPCell cells[] = new PdfPCell[3];
        cells[1] = new PdfPCell(new Phrase(title, getFont(14)));
        cells[2] = new PdfPCell(new Phrase(value, getFont(15)));
        return cells;
    }

    private PdfPCell[] getPdfPNullCells() {
        PdfPCell[] cellsNull = new PdfPCell[5];
        cellsNull[0] = new PdfPCell(new Paragraph("  "));   //单元格内容
        cellsNull[0].setColspan(5);
        cellsNull[0].setPadding(4);
        return cellsNull;
    }

    private PdfPCell[] getPdfPCells(String titles, String params) throws DocumentException, IOException {
        // 中文字体,解决中文不能显示问题
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font font = new Font(bfChinese);
        PdfPCell[] cells = new PdfPCell[5];
        cells[0] = new PdfPCell(new Paragraph(titles, font));   //单元格内容
        cells[0].setHorizontalAlignment(Element.ALIGN_CENTER);  //水平居中
        cells[0].setVerticalAlignment(Element.ALIGN_MIDDLE);    //垂直居中
        cells[0].setPadding(7);
        cells[1] = new PdfPCell(new Paragraph(StringUtils.isNotEmpty(params) ? params : "暂无数据", font));   //单元格内容
        cells[1].setColspan(4);
        cells[1].setPadding(7);
        cells[1].setHorizontalAlignment(Element.ALIGN_CENTER);  //水平居中
        cells[1].setVerticalAlignment(Element.ALIGN_MIDDLE);    //垂直居中
        return cells;
    }

    private Font getFont(int size) throws DocumentException, IOException {
        // 微软雅黑
        BaseFont chinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        // 普通中文字体
        Font static_FONT_CHINESE = new Font(chinese, size, Font.NORMAL);// Font.BOLD为加粗
        return static_FONT_CHINESE;
    }

    /**
     * 统一设置每一行单元格样式
     *
     * @param cells
     * @return
     */
    private PdfPCell[] setCell(PdfPCell[] cells) {
        for (int i = 0; i < cells.length; i++) {
            if (cells[i] != null) {
                cells[i].setPadding(7);
                cells[i].setHorizontalAlignment(Element.ALIGN_CENTER);  //水平居中
                cells[i].setVerticalAlignment(Element.ALIGN_MIDDLE);    //垂直居中
            }
        }
        return cells;
    }

    /**
     * 设置每一个单元格样式
     *
     * @param cell
     * @return
     */
    private PdfPCell setCell(PdfPCell cell) {
        cell.setPadding(7);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);  //水平居中
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);    //垂直居中
        return cell;
    }

    /**
     * 得到想要字体
     *
     * @param zt
     * @return
     */
    private Font getFont(String zt) throws DocumentException, IOException {
        Font font = null;
        switch (zt) {
            case "CN":
                // 中文字体,解决中文不能显示问题
                BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                font = new Font(bfChinese);
                break;
        }
        return font;
    }

    private String getCount(List<String> nameLists, String from) {
        JSONArray wenshuList = JSONArray.parseArray(config.getProperty("wenshu"));
        Map<String, Integer> nameMap = new HashMap<>();
        nameLists.forEach(name -> {
            Integer counts = nameMap.get(name);
            nameMap.put(name, counts == null ? 1 : ++counts);
        });
        StringBuffer buffer = new StringBuffer();
        if ("zxgg".equals(from)) {
            for (Map.Entry<String, Integer> entry : nameMap.entrySet()) {
                if ("0".equals(entry.getKey())) {
                    buffer.append("执行中: " + entry.getValue() + "件；");
                } else if ("1".equals(entry.getKey())) {
                    buffer.append("已结案: " + entry.getValue() + "件；");
                } else {
                    buffer.append("特殊状态: " + entry.getValue() + "件；");
                }
            }
        } else if ("cpws_1".equals(from)) {
            for (Map.Entry<String, Integer> entry : nameMap.entrySet()) {
                if (wenshuList.contains(entry.getKey())) {
                    buffer.append(entry.getKey() + ": " + entry.getValue() + "份；");
                } else {
                    buffer.append("其它：" + entry.getValue() + "份；");
                }
            }
        } else if ("cpws_2".equals(from)) {
            for (Map.Entry<String, Integer> entry : nameMap.entrySet()) {
                buffer.append(entry.getKey() + "出现: " + entry.getValue() + "次；");
            }
        } else {
            for (Map.Entry<String, Integer> entry : nameMap.entrySet()) {
                buffer.append(entry.getKey() + ": " + entry.getValue() + "次");
            }
        }
        return buffer.toString();
    }
}
